<?php
class GuaDanAction extends CommonAction {
    private $GuaDan;
    private $TypeBox;
    private $ChongZhi;
    private $User;
    private $Type;

    public function __construct(){
        parent::__construct();
        $this->checkAuth();
        $this->GuaDan = D('GuaDan');
        $this->TypeBox = D('TypeBox');
        $this->ChongZhi = D('ChongZhi');
        $this->User = D('User');
        $this->Type = D('Type');
    }

    public function index(){
        $per_num = 10;
        $page = is_numeric($_GET['page']) ? $_GET['page'] : 1;
        $count = $this->GuaDan->where('userid='.$_SESSION['USER_KEY_ID'])->count();
        $page_num = ceil($count/$per_num);
        if($page < 1){
            $page = 1;
        }elseif($page > $page_num){
            $page = $page_num;
        }

        $list=$this->GuaDan->join('t_type_box t on (t.id=t_gua_dan.typeboxid)')->join('t_type t1 on t1.id=t.name1')->join('t_type t2 on t2.id=t.name2')->where('t_gua_dan.userid='.$_SESSION['USER_KEY_ID'])->field('t_gua_dan.*,t.name1,t.name2,t1.nickname as names1,t2.nickname as names2')->limit(($page-1)*$per_num.','.$per_num)->select();

        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('page_num',$page_num);
        $this->display('./Tpl/Home/user_guadan.html');
    }

    public function work(){
        if(!$this->sysv['buyflag']){
            $this->error('购买开关未打开！');
        }
        if(!chkNum($_POST['typeboxid']) || !chkNum($_POST['price']) || !chkNum($_POST['num']) || !chkStr($_POST['transpw'])){
            $this->error("提交失败！");
            exit;
        }

        $u = $this->User->where('id='.$_SESSION['USER_KEY_ID'])->find();
        if(md5($_POST['transpw']) != $u['transpw']){
            $this->error('交易密码错误！');
            exit;
        }

        $tb = $this->TypeBox->where('id='.$_POST['typeboxid'])->find();
        $goods = $this->Type->where('id='.$tb['name1'])->find();

        $c = $this->GuaDan->where('typeboxid='.$_POST['typeboxid'].' and to_days(addtime)<to_days(now())')->order('id desc')->find();
        if($c){
            if($_POST['price']>($c['price']+$c['price']*$goods['up']/100))
                $this->error('交易价格超过'.$goods['up'].' %！');
            if($_POST['price']<($c['price']-$c['price']*$goods['down']/100))
                $this->error('交易价格低于下限'.$goods['down'].' %！');
        }

        $price = coin($_POST['price']);
        $num = $n = coin($_POST['num']);
         $tbid = $_POST['typeboxid'];
        $flag = $_POST['flag'] ? $_POST['flag'] : 0;
         $userid = $_SESSION['USER_KEY_ID'];
        

        $mo = new Model();
        $mo->startTrans();

        $t1_cz = $this->ChongZhi->where('userid='.$userid.' and typeid='.$tb['name1'])->find();
        $t2_cz = $this->ChongZhi->where('userid='.$userid.' and typeid='.$tb['name2'])->find();

        if($flag==0){
            if($_POST['num']<$goods['sellmin'])
                $this->error('卖出量低于下限！');

            if($num > $t1_cz['goldnum']) {$this->error('余额不够！');exit;}

            $orders = $this->GuaDan->where('flag=1 and typeboxid='.$tbid.' and price>='.$price)->order('price desc,num desc,addtime asc')->select();

            if($orders){
                foreach($orders as $k => $v){
                    $trans = coin($n < $v['num'] ? $n : $v['num']);
                    if($n<=0) break;
                    if($trans<=0) break;

                    if($n >= $trans){
                        $n -= $trans;
                        $sum = coin($trans * $price);
                    }else{ break; }
					
					$data=array();//释放data数组
                    $data['sum'] = $sum;
                    $data['price'] = $price;
                    $data['num'] = $trans;
                    $data['flag'] = 0;
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $rs1 = $mo->table('t_trans_log')->add($data);
                   

                    //买入方
                    $t1_ocz = $this->ChongZhi->where('userid='.$v['userid'].' and typeid='.$tb['name1'])->find();
                    $t2_ocz = $this->ChongZhi->where('userid='.$v['userid'].' and typeid='.$tb['name2'])->find();

                    $rs2 = $mo->table('t_chong_zhi')->save(array(
                        'id'=>$t1_ocz['id'],
                        'goldnum'=>coin($t1_ocz['goldnum'] + $trans)
                    ));

                    $rs3 = $mo->table('t_chong_zhi')->save(array(
                        'id'=>$t2_ocz['id'],
                        'gdgold'=>coin($t2_ocz['gdgold'] - $trans * $v['price'])
                    ));

                    if($v['num'] > $trans){
                        $rs4 = $mo->table('t_gua_dan')->save(array(
                            'id'=>$v['id'],
                            'num'=>coin($v['num']-$trans)
                        ));
                    }else{
                        $rs4 = $mo->table('t_gua_dan')->where('id='.$v['id'])->delete();
                    }
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $data['sum'] = coin($v['price'] * $trans);
                    $data['price'] = $v['price'];
                    $data['num'] = $trans;
                    $data['flag'] = 1;
                    $data['zhu'] = 1;
                    $rs5 = $mo->table('t_trans_log')->add($data);

                }

                $remain = $num - $n;
                if($n > 0){
                    $t['gdgold'] = coin($t1_cz['gdgold'] + $n);
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $data['total'] = coin($price * $n);
                    $data['price'] = $price;
                    $data['num'] = $n;
                    $data['flag'] = 0;
                    $rs8 = $mo->table('t_gua_dan')->add($data);
                   
                }else{
                    $rs8 = true;
                }
                if($remain > 0){
                    $transsum = coin($remain * $price);
                }else{
                    $mo->rollback();
                    $this->error('操作失败001！');
                }

                $rs6 = $mo->table('t_chong_zhi')->save(array(
                    'id' => $t1_cz['id'],
                    'goldnum' => coin($t1_cz['goldnum'] - $num)
                ));
                if($transsum > 0)
                    $rs7 = $mo->table('t_chong_zhi')->save(array(
                        'id' => $t2_cz['id'],
                        'goldnum' => coin($t2_cz['goldnum'] + $transsum)
                    ));
                else
                    $rs7=true;

                if($rs1 && $rs2 && $rs3 && $rs4 && $rs5 && $rs6 && $rs7 && $rs8){
                    $mo->commit();
                    $this->success('操作成功！');
                }else{
                    $mo->rollback();
                    $this->error('操作失败002！');
                }
            }else{
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                $data['total'] = coin($price * $num);
                $data['price'] = $price;
                $data['num'] = $num;
                $data['flag'] = 0;
                $rs1 = $mo->table('t_gua_dan')->add($data);


                $t['id'] = $t1_cz['id'];
                $t['goldnum'] = coin($t1_cz['goldnum'] - $num);
                $t['gdgold'] = coin($t1_cz['gdgold'] + $num);

                $rs2 = $mo->table('t_chong_zhi')->save($t);

                if($rs1 && $rs2){
                    $mo->commit();
                    $this->success('操作成功！');
                }else{
                    $mo->rollback();
                    $this->error('操作失败003！');
                }
            }
        }else{
            if($_POST['num']<$goods['buymin'])
                $this->error('购买量低于下限！');

            $total = coin($price * $num);
            if($total > $t2_cz['goldnum']) {$this->error('余额不够！');exit;}

            $orders = $this->GuaDan->where('flag=0 and typeboxid='.$tbid.' and price<='.$price)->order('price asc,num desc,addtime asc')->select();
            if($orders){
                foreach($orders as $k => $v){
                    $trans = coin($n < $v['num'] ? $n : $v['num']);
                    if($n<=0) break;
                    if($trans<=0) break;

                    if($n >= $trans){
                        $n -= $trans;
                        $sum = coin($trans * $price);
                    }else{ break; }

                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $data['sum'] = $sum;
                    $data['price'] = $price;
                    $data['num'] = $trans;
                    $data['flag'] = 1;
                    $rs1 = $mo->table('t_trans_log')->add($data);


                    $t1_ocz = $this->ChongZhi->where('userid='.$v['userid'].' and typeid='.$tb['name1'])->find();
                    $t2_ocz = $this->ChongZhi->where('userid='.$v['userid'].' and typeid='.$tb['name2'])->find();

                    $rs2 = $mo->table('t_chong_zhi')->save(array(
                        'id'=>$t2_ocz['id'],
                        'goldnum'=>coin($t2_ocz['goldnum'] + $trans * $v['price'])
                    ));

                    $rs3 = $mo->table('t_chong_zhi')->save(array(
                        'id'=>$t1_ocz['id'],
                        'gdgold'=>coin($t1_ocz['gdgold'] - $trans)
                    ));

                    if($v['num'] > $trans){
                        $rs4 = $mo->table('t_gua_dan')->save(array(
                            'id'=>$v['id'],
                            'num'=>coin($v['num']-$trans)
                        ));
                    }else{
                        $rs4 = $mo->table('t_gua_dan')->where('id='.$v['id'])->delete();
                    }
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $data['sum'] = coin($v['price'] * $trans);
                    $data['price'] = $v['price'];
                    $data['num'] = $trans;
                    $data['flag'] = 0;
                    $data['zhu'] = 1;
                    $rs5 = $mo->table('t_trans_log')->add($data);

                }

                $remain = $num - $n;
                if($n > 0){
                    $t['gdgold'] = coin($t2_cz['gdgold'] + $n * $price);
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                    $data['total'] = coin($price * $n);
                    $data['price'] = $price;
                    $data['num'] = $n;
                    $data['flag'] = 1;
                    $rs8 = $mo->table('t_gua_dan')->add($data);

                }else{
                    $rs8 = true;
                }
                if($remain > 0){
                    $transsum = $remain;
                }else{
                    $mo->rollback();
                    $this->error('操作失败004！');
                }

                $t['id'] = $t2_cz['id'];
                $t['goldnum'] = coin($t2_cz['goldnum'] - $num * $price);

                $rs6 = $mo->table('t_chong_zhi')->save($t);

                if($transsum > 0)
                    $rs7 = $mo->table('t_chong_zhi')->save(array(
                        'id' => $t1_cz['id'],
                        'goldnum' => coin($t1_cz['goldnum'] + $transsum)
                    ));
                else
                    $rs7=true;

                //if($rs1 && $rs2 && $rs3 && $rs4 && $rs5 && $rs6 && $rs7 && $rs8){
                    $mo->commit();
                    $this->success('操作成功！');
                //}else{
                 //   $mo->rollback();
               //     $this->error('操作失败005！'.
                //        '|'.$rs1.'|'.$rs2 .'|'. $rs3.'|'. $rs4 .'|'. $rs5 .'|'. $rs6.'|'.$rs7 .'|'.$rs8.'|');
                //}
            }else{
                    $data=array();//释放data数组
					$data['typeboxid'] = $tbid;
					$data['userid'] = $userid;
					$data['addtime'] = date('Y-m-d H:i:s',time());
                $data['total'] = coin($price * $num);
                $data['price'] = $price;
                $data['num'] = $num;
                $data['flag'] = 1;
                $rs1 = $mo->table('t_gua_dan')->add($data);


                $t['id'] = $t2_cz['id'];
                $t['goldnum'] = coin($t2_cz['goldnum'] - $num * $price);
                $t['gdgold'] = coin($t2_cz['gdgold'] + $num * $price);

                $rs2 = $mo->table('t_chong_zhi')->save($t);

                if($rs1 && $rs2){
                    $mo->commit();
                    $this->success('操作成功！');
                }else{
                    $mo->rollback();
                    $this->error('操作失败006！');
                }
            }
        }
    }

    public function cancel(){
        if(empty($_GET['id'])){
            $this->error('操作失败！');
        }

        $mo = new Model();
        $mo->startTrans();

        $value = $this->GuaDan->where('id='.$_GET['id'])->find();
        $tb = $mo->table('t_type_box')->where('id='.$value['typeboxid'])->find();

        if($value['flag']==0){
            $t1_cz = $this->ChongZhi->where('userid='.$value['userid'].' and typeid='.$tb['name1'])->find();

            $data['id'] = $t1_cz['id'];
            $data['gdgold'] = coin($t1_cz['gdgold'] - $value['num']);
            $data['goldnum'] = coin($t1_cz['goldnum'] + $value['num']);

            $rs = $mo->table('t_chong_zhi')->save($data);

        }else{
            $t2_cz = $this->ChongZhi->where('userid='.$value['userid'].' and typeid='.$tb['name2'])->find();

            $data['id'] = $t2_cz['id'];
            $data['gdgold'] = coin($t2_cz['gdgold'] - $value['num'] * $value['price']);
            $data['goldnum'] = coin($t2_cz['goldnum'] + $value['num'] * $value['price']);

            $rs = $mo->table('t_chong_zhi')->save($data);
        }

        $rs1 = $this->GuaDan->where('id='.$_GET['id'])->delete();

        if($rs && $rs1){
            $mo->commit();
            $this->success('操作成功！');
        }else{
            $mo->rollback();
            $this->error('操作失败！');
        }
    }
}